package com.wfs.aoawlms.filter;

import com.alibaba.fastjson.JSONObject;
import com.wfs.aoawlms.pojo.Result;
import com.wfs.aoawlms.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = {"/**","/**"})
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String options = "OPTIONS";
        // OPTIONS请求略过
        if(options.equals(request.getMethod())){
            filterChain.doFilter(request,response);
            return;
        }
        //1 获取请求url
        String url = request.getRequestURI().toString();
        log.info("请求路径；{}",url);
        //2 判断请求url中是否包含login，若包含，说明是登录操作，放行
        if(url.contains("/login")){
            filterChain.doFilter(request,response);
            return;
        }
        // 获取请求头中的令牌（token）
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader!= null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7);
            log.info("从请求头中获取的令牌:{}",token);
            // 后续的验证逻辑，如判断令牌是否存在、解析token等操作使用这个正确的token
            //4 判断令牌是否存在，若不存在，返回错误结果（未登录）
            if(!StringUtils.hasLength(token)){
                log.info("Token不存在");
                Result responseResult = Result.error("NOT_LOGIN");
                String json = JSONObject.toJSONString(responseResult);
                // 响应
                response.getWriter().write(json);
                return;
            }
            // 5 解析token，若解析失败，返回错误结果（未登录
            try{
                log.info("接收到并解析的token",token);
                JwtUtils.parseJWT(token);
            }catch (Exception e){
                log.info("令牌解析失败！");
                Result responseResult = Result.error("NOT_LOGIN");
                String json = JSONObject.toJSONString(responseResult);
                response.setContentType("application/json/charset=utf-8");
                // 设置CORS头部信息
                response.setHeader("Access-Control-Allow-Origin", "*");
                // 响应
                response.getWriter().write(json);
                return;
            }
        } else {
            // 处理没有正确Authorization头部的情况，如返回错误结果
            log.info("未找到正确的Authorization头部");
            Result responseResult = Result.error("NOT_LOGIN");
            String json = JSONObject.toJSONString(responseResult);
            // 响应
            response.getWriter().write(json);
            return;
        }
        //6 放行
        filterChain.doFilter(request,response);
    }

}
